<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="formRules" label-width="120px">
      <el-form-item label="解决方案名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入解决方案名称" />
      </el-form-item>
      <el-form-item label="解决方案介绍" prop="info">
        <el-input v-model="formData.info" placeholder="请输入解决方案介绍" />
      </el-form-item>
      <el-form-item label="解决方案图片" prop="file">
        <div style="display: flex;">
          <UploadFile @success="handleUploadFiles" ref="imgUpload" :limit="1" :fileList="fileList"
            :pasteImg="imageUrl" />
          <div class="gap-2 file-wrap" v-if="formType == 'update'">
            <template v-if="fileList && fileList.length">
              <viewFile :file-list="viewImgFiles" />
            </template>
            <span v-else>暂无图片</span>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="路由地址" prop="url">
        <el-input v-model="formData.url" clearable placeholder="请输入路由地址" />
      </el-form-item>
      <el-form-item label="显示排序" prop="sort">
        <el-input-number v-model="formData.sort" :min="0" clearable controls-position="right" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import * as PortalApi from '@/api/portal'
import UploadFile from '../upload/UploadFileCom.vue'
import viewFile from '../upload/ViewImgFileCom.vue'

defineOptions({ name: 'SolutionForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: '',
  info: '',
  url: '',
  sort: undefined,
  whetherNew: 1,
  whetherNowExperience: 1,
  whetherViewDetails: 1
})
const checkFile = (rule: any, value: any, callback: any) => {
  let val = fileList.value
  if (!val.length) {
    return callback(new Error('图片不能为空'))
  } else {
    callback()
  }
}
const formRules = reactive({
  name: [{ required: true, message: '解决方案名称不能为空', trigger: 'blur' }],
  url: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '显示顺序不能为空', trigger: 'blur' }],
  info: [{ required: true, message: '解决方案介绍不能为空', trigger: 'blur' }],
  file: [{ validator: checkFile, trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      let data = await PortalApi.getSolution(id)
      fileList.value = JSON.parse(data.picture)
      filterImageAndNonImageFiles(fileList.value, 'info')
      formData.value = data
    } finally {
      formLoading.value = false
    }
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    info: '',
    url: '',
    sort: undefined,
    whetherNew: 1,
    whetherNowExperience: 1,
    whetherViewDetails: 1
  }
  fileList.value = []
  formRef.value?.resetFields()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    const formDataObj = new FormData()
    if (fileList.value.length) {
      fileList.value.forEach((item) => {
        if (item.raw) {
          formDataObj.append(`files`, item.raw, item.name)
        } else {
          formDataObj.append(`files`, new Blob([item.url], { type: '' }))
        }
      })
    } else {
      formDataObj.append('files', new Blob([], { type: '' }))
    }

    if (formType.value === 'create') {
      formDataObj.append(
        'solutionSaveReqVO ',
        new Blob([JSON.stringify(data)], { type: 'application/json' })
      )
      await PortalApi.createSolution(formDataObj)
      message.success(t('common.createSuccess'))
    } else {
      formDataObj.append(
        'solutionSaveReqVO ',
        new Blob([JSON.stringify(data)], { type: 'application/json' })
      )
      await PortalApi.updateSolution(formDataObj)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const imgUpload = ref()
const fileList = ref([] as any)
const imageUrl = ref([] as any)
const viewImgFiles = ref([] as any)
// 创建问题文件操作完成
const handleUploadFiles = (files) => {
  fileList.value = files
  filterImageAndNonImageFiles(fileList.value, 'info')
}

function filterImageAndNonImageFiles(filesArray, type) {
  viewImgFiles.value = []
  filesArray.length && filesArray.forEach((file) => {
    // 判断文件是否为图片，可以通过检查MIME类型或文件扩展名
    if (isImageFile(file) && file.url) {
      viewImgFiles.value.push(file)
    }
  })
}
// 判断文件是否为图片的辅助函数
function isImageFile(file) {
  const fileName = file.name
  const fileExtension = fileName.split('.').pop().toLowerCase()
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']
  return imageExtensions.includes(fileExtension)
}
</script>
